const Reader = require('../models/Reader');
const jwt = require('jsonwebtoken');
const { secret } = require('../config/jwt');

exports.register = async (ctx) => {
  const { username, password, role } = ctx.request.body;
  try {
    const reader = await Reader.create({ username, password, role });
    ctx.status = 201;
    ctx.body = { message: 'User registered successfully', reader };
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

exports.login = async (ctx) => {
  const { username, password } = ctx.request.body;
  try {
    const reader = await Reader.findOne({ where: { username } });
    if (!reader) {
      ctx.status = 401;
      ctx.body = { error: 'Invalid credentials' };
      return;
    }

    const isMatch = (password === reader.password);
    if (!isMatch) {
      ctx.status = 401;
      ctx.body = { error: 'Invalid credentials' };
      return;
    }

    const token = jwt.sign({ id: reader.reader_id, role: reader.role }, secret, { expiresIn: '1h' });
    ctx.body = { token };
  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: error.message };
  }
};